package com.compass.network.repository



import com.compass.mobile.network.error.ApiException
import com.compass.mobile.network.error.ERROR
import com.compass.mobile.network.response.BaseResponse

import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import kotlinx.coroutines.withTimeout

/**
 *
 * @desc   基础仓库
 */
open class BaseRepository {

    /**
     * IO中处理请求
     */
    suspend fun <T> requestResponse(requestCall: suspend () -> BaseResponse<T>?): T? {
        val response = withContext(Dispatchers.IO) {
            withTimeout(10 * 1000) {
                requestCall()
            }
        } ?: return null

        if (response.isFailed()) {
            response.msg?.let {
                throw ApiException(response.code, it)
            }?:kotlin.run {
                throw ApiException(response.code, ERROR.NOT_FOUND.errMsg)
            }
        }
        return response.data
    }
}